package com.tuniondata.netty.server;

import com.tuniondata.netty.common.NamedThreadFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
/**
 * @author yuxinchao
 */
@Component
@ConfigurationProperties(prefix = "api-server")
public class ApiServer {
    private static final Logger log = LoggerFactory.getLogger(ApiServer.class);

    private int port;

    public ApiServer() {
        new Thread("api-binary-server") {
            @Override
            public void run() {
                startServer();
            }
        }.start();
    }

    public void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(2, new NamedThreadFactory("api-netty-boss-group"));
        EventLoopGroup workerGroup = new NioEventLoopGroup(4, new NamedThreadFactory("api-netty-worker-group"));

        try {
            String processName = ManagementFactory.getRuntimeMXBean().getName();
            log.info("starting binary api server: {}, running at port:{}, process: {}", this, port, processName);

            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024);
            b.childHandler(new ChildChannelHandler());

            ChannelFuture channelFuture = b.bind(port).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("api server exception", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void setPort(int port) {
        this.port = port;
    }
}
